<template>
  <div id="outWaveStrategyGroupDeawer">
    <el-card class="base-card">
      <div slot="header">
        <span>{{ $t("wave.groupinfo") }}</span>
      </div>
      <div class="card-content" :style="{ height: bodyHeight + 'px' }">
        <el-form 
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="base-form"
         
        >
          <el-form-item
            :label="$t('wave.wavegroupname')"
            prop="group_name"
            class="base-width-25"
          >
            <el-input v-model="ruleForm.group_name"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('wave.validrang')"
            prop="time"
            class="base-width-50"
          >
            <el-date-picker
              v-model="ruleForm.time"
              type="datetimerange"
              :unlink-panels="true"
              :picker-options="pickerOptions"
              range-separator="至"
              :start-placeholder="$t('app.startDate')"
              :end-placeholder="$t('app.endDate')"
              align="right"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="type" style="padding:0 8px">
            <el-checkbox
              :label="$t('app.isdefault')"
              name="type"
              v-model="ruleForm.type"
            ></el-checkbox>
          </el-form-item>
        </el-form>
        <h5 style="padding:0 8px;display:flex;justify-content: space-between;">
          <span style="font-weight:bold;">{{ $t("wave.wavestrlist") }}</span>
        </h5>
        <ag-grid
          class="base-grid no-edit"
          ref="table"
          :hasCheck="true"
          :hasIndex="false"
          :hasEdit="false"
          v-model="gridObj"
          :defaultColDef="defaultColDef"
          :highlightCurrentRow="false"
          :disabled="true"
          :data="rowData"
          :rules="rules"
          :height="tableHeight"
          :tmsShowFilter="false"
          :columnConfig="columnConfig"
          :extraColumns="extraColumns"
          :showSummary="false"
          :pagination="false"
          :pageDetail="false"
          :searchBox="false"
          :tableSettingVisible.sync="showTableSetting"
          :page="page"
          :pageSize="pageSize"
          :total="total"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @grid-ready="agGridReady"
        >
        </ag-grid>
        <div class="btns">
          <el-button type="primary" :disabled="!this.btnPermNameList.includes('WM05010203')" @click="save">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="cancel" :disabled="!this.btnPermNameList.includes('WM05010204')">{{ $t("common.cancel") }}</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  outWaveStrategyGroupSave,
  outWaveStrategyGroupEdit,
  outWaveStrategyGroupQuery,
} from "@/api/business/wave";
import agGridBaseMixin from "@/mixins/AgGridBaseMixin";
import baseMixin from "@/mixins/BaseMixin";

export default {
  name: "outWaveStrategyGroupDeawer",
  mixins: [baseMixin,agGridBaseMixin],
  data() {
    return {
      selectedData: [],
      selectedDataDefault: [],
      newFlag: false,
      ruleForm: {
        group_name: "",
        time: [],
        type: false,
      },
      rules: {
        group_name: [
          { required: true, message: "请输入波次组合名称", trigger: "blur" },
        ],
        time: [
          {
            type: "array",
            required: true,
            message: "请选择生效时间区间",
            trigger: "change",
          },
        ],
      },
      pickerOptions: {
        shortcuts: [
          {
            text: this.$t('app.lastweek'),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: this.$t('app.lastmonth'),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: this.$t('app.lastquarter'),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      bodyHeight: 0,
      tableHeight: 0,
      columnConfig: {
        menu_id: 946,
        menu_code: "outWaveStrategyGroup",
        menu_list_code: "outWaveStrategyGroupDtl",
      },
      defaultColDef: {},
    };
  },
  mounted() {
    this.bodyHeight = this.getHeight(window);
    this.tableHeight = this.getHeight(window, 230);
    if (Object.keys(this.$store.state.skip).length !== 0) {
      let data = this.$store.state.skip;
      this.newFlag = data.newFlag;
    } else {
      this.newFlag = this.$store.state.newFlag;
    }
    this.getTableData(1, {});
    if (!this.newFlag) {
      // 接收列表传输的数据
      let obj = this.$store.state.routeData;
      let validTime = obj.validTime;
      let invalidTime = obj.invalidTime;
      // 赋值编辑页面对象-转换时间对象
      this.ruleForm = {
        group_name: obj.groupName,
        time: [new Date(validTime).getTime(), new Date(invalidTime).getTime()],
        type: obj.isDefault === 1 ? true : false,
        id: obj.id,
      };
    } else {
      this.ruleForm = {
        group_name: "",
        time: [],
        type: false,
      };
    }
  },
  methods: {
    handleSelectionChange(data) {
      this.selectedData = data;
    },
    save() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let data = {};
          data.groupName = this.ruleForm.group_name;
          data.validTime = this.ruleForm.time[0];
          data.invalidTime = this.ruleForm.time[1];
          data.isDefault = this.ruleForm.type ? 1 : 0;
          data.warehouseId = this.$store.state.wms;
          let arr = [];
          this.selectedData.forEach((item) => {
            arr.push({
              waveStrategyId: parseInt(item.filterid),
              waveStrategyName: item.filtername,
              waveStrategyType: item.filtername,
              warehouseId: this.$store.state.wms,
            });
          });
          data.outWaveStrategyGroupDtls = arr;
          if (arr.length === 0) {
            this.$message.error(this.$t('msg.msg16'));
            return;
          }
          if (this.newFlag) {
            outWaveStrategyGroupSave(data)
              .then((res) => {
                  this.$message.success(this.$t('app.addMes'));
                  this.cancel();
              })
              .catch((e) => {
                console.log(e.data);
                this.$message.error(e.data.returnMgr);
              });
          } else {
            data.id = this.ruleForm.id;
            outWaveStrategyGroupEdit(data).then((res) => {
                this.$message.success(this.$t('app.upMes'));
                this.cancel();
            });
          }
        } else {
          this.$message.error(this.$t('msg.msg69'));
          return false;
        }
      });
    },
    cancel() {
      this.$router.push({ name: "outWaveStrategyGroup" });
    },
    handleCurrentChange(data) {
      console.log(data);
    },
    async getTableData(page, data) {
      let res = await this.$api.post(`/queryWpFilterList`, data);
      
        this.rowData = res.page.list;
        this.pageSize = res.page.pageSize;
        this.page = res.page.curpage;
        this.total = res.page.total;
    },
    async selectedRows() {
      await outWaveStrategyGroupQuery(this.$store.state.routeData.id).then(
        (res) => {
            this.selectedDataDefault = res.bean.outWaveStrategyGroupDtls;
            if (this.selectedDataDefault.length != 0) {
              // this.selectedDataDefault.forEach(item => {
              //     console.log(this.gridObj.api.forEachNode);
              //     this.gridObj.api.forEachNode(node => {
              //         if (parseInt(node.data.filterid) === item.waveStrategyId) {
              //             node.setSelected(true);
              //         }
              //     })
              // })
              let arr = [];
              this.selectedDataDefault.forEach((item) => {
                arr.push(item.waveStrategyId);
              });
              const nodes = this.gridObj.api.getRenderedNodes();
              if (nodes.length != 0) {
                nodes.forEach((node) => {
                  console.log(node.data.filterid);
                  if (arr.indexOf(parseInt(node.data.filterid)) >= 0) {
                    // 如果存在，则说明字段已选中
                    this.gridObj.api.selectNode(node, true);
                  }
                });
              } else {
                this.selectedRows();
              }
            }
          
        }
      );
    },
    agGridReady(params) {
      this.gridObj = params;
      if (!this.newFlag) {
        this.selectedRows();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
#outWaveStrategyGroupDeawer {
  overflow: hidden;
  height: 100%;

  .btns {
    width: 100%;
    text-align: center;
  }

  ::v-deep .el-range-separator {
    line-height: 24px;
  }

  ::v-deep .el-date-editor .el-range__close-icon {
    line-height: 24px;
  }
}
</style>
